package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyFuManTongMask;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExChangeFuManTongMask;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * QD安心-v3出-福满通API2-8分润
 * @ Author 江小游
 * @ Date 2025/6/13 15:16
 */
@ApiPlan(productId = "43", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatFuManTongPhoneMask implements ApiPlatformPhoneMaskConvertHandler {

    private static final String KEY = "ba4810e6d9ebd7abec24e2be6e4f8fc2";
    private static final String CHANNEL_CODE = "KZFZJZBKFS";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        // 实体类
        ApiPlatDataExChangeFuManTongMask apiPlatDataExChangeFuManTong = new ApiPlatDataExChangeFuManTongMask();
        // 扩展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        apiPlatDataExChangeFuManTong.setPhone(apiDataExchangeParameter.getPhoneMask());
        apiPlatDataExChangeFuManTong.setRealName("浩安星");
        apiPlatDataExChangeFuManTong.setAge(apiFieldConverter.getAgeInt());
        //  性别
        Integer sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatDataExChangeFuManTong.setGender(sex);
        apiPlatDataExChangeFuManTong.setCity(apiDataExchangeParameter.getCity());
        apiPlatDataExChangeFuManTong.setCityCode(apiDataExchangeParameter.getAreaCode());
        //  公积金
        apiPlatDataExChangeFuManTong.setAccumulationFund(apiFieldConverter.hasProvidentFundToNumber());
        //  社保
        apiPlatDataExChangeFuManTong.setSocialSecurity(apiFieldConverter.hasSocialSecurityToNumber());
        //  房产
        apiPlatDataExChangeFuManTong.setHouse(apiFieldConverter.hasRealEstateInfoToNumber());
        //  车
        apiPlatDataExChangeFuManTong.setVehicle(apiFieldConverter.hasCarInfoToNumber());
        //  保单
        apiPlatDataExChangeFuManTong.setInsurance(apiFieldConverter.hasInsurancePolicyToNumber());
        //  描述：芝麻分0:无芝麻分1:600分以下2:600-650分3:650-700分4:700分以上默认1
        Integer zhima = ChooseEq.create(apiDataExchangeParameter.getSesameCredit())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .end(1);
        apiPlatDataExChangeFuManTong.setSesameScore(zhima);
        //  职业身份1-上班族2-公务员/事业单位3-私营业主4-个体户5-其他默认1
        Integer professional = ChooseEq.create(apiDataExchangeParameter.getCareer())
                .when("1", 1)
                .when("2", 5)
                .when("3", 3)
                .when("4", 2)
                .when("5", 4)
                .end(1);
        apiPlatDataExChangeFuManTong.setProfessional(professional);
        // ip
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            apiPlatDataExChangeFuManTong.setIp(apiPlatDataExChangeFuManTong.getIp());
        } else {
            apiPlatDataExChangeFuManTong.setIp("127.0.0.1");
        }
        // 用户客户端
        apiPlatDataExChangeFuManTong.setClient(1);
        //  贷款金额
        apiPlatDataExChangeFuManTong.setAmount(apiFieldConverter.getLoanAmountInt());
        //  借款期限
        Integer loanTerm = ChooseEq.create(apiDataExchangeParameter.getLoanTerm())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .when("5", 5)
                .when("6", 5)
                .end(3);
        apiPlatDataExChangeFuManTong.setLoanTerm(loanTerm);
        //  借款用途1-购房 2-购车 3-住房装修4-教育深造5-休闲旅游6-个人消费7-房租缴纳8-其他贷款默认6*/
        Integer loanUse = ChooseEq.create(apiDataExchangeParameter.getLoanPurpose())
                .when("1", 5)
                .when("2", 4)
                .when("3", 8)
                .when("4", 3)
                .when("5", 8)
                .when("6", 6)
                .end(6);
        apiPlatDataExChangeFuManTong.setLoanUse(loanUse);
        //  信用卡
        Integer creditCard = ChooseEq.create(apiDataExchangeParameter.getCreditLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .when("6", 1)
                .end(0);
        apiPlatDataExChangeFuManTong.setCreditCard(creditCard);
        //  白条
        Integer bt = ChooseEq.create(apiDataExchangeParameter.getBtLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .end(0);
        apiPlatDataExChangeFuManTong.setBaitiao(bt);
        // 花呗
        Integer hb = ChooseEq.create(apiDataExchangeParameter.getHbLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .end(0);
        apiPlatDataExChangeFuManTong.setHuabei(hb);
        //  月收入
        Integer salary = ChooseEq.create(apiDataExchangeParameter.getMonthlySalary())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .when("5", 5)
                .end(2);
        apiPlatDataExChangeFuManTong.setMonthIncome(salary);
        //  工资发放
        Integer salaryMethod = ChooseEq.create(apiDataExchangeParameter.getYearsService())
                .when("1", 1)
                .when("2", 3)
                .when("3", 2)
                .end(2);
        apiPlatDataExChangeFuManTong.setSalaryType(salaryMethod);
        //  月收入
        Integer education = ChooseEq.create(apiDataExchangeParameter.getEducationAttainment())
                .when("1", 1)
                .when("2", 1)
                .when("3", 1)
                .when("4", 2)
                .when("5", 3)
                .when("6", 5)
                .end(2);
        apiPlatDataExChangeFuManTong.setEducation(education);
        //  营业执照
        apiPlatDataExChangeFuManTong.setBusinessLicense(apiFieldConverter.hasBizLicenseYearToNumber());
        //  加密方法
        AES aes = AES.createEcb(KEY.getBytes());
        String json = JsonUtils.toJson(apiPlatDataExChangeFuManTong);
        String encrypt = aes.encryptToBase64Str(json);
        Map<Object, Object> dataMap = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("content", encrypt);
        });
        return JsonUtils.toJson(dataMap);
    }


    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        JSONArray resData = JsonUtils.get(respJson).getJSONArray("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();

        for (int i = 0; i < resData.size(); i++) {
            JSONObject item = resData.getJSONObject(i);
            if (ValidParam.isNotNull(item)) {
                //  缺失用户协议
                BigDecimal price = item.getBigDecimal("originalPrice");
                String logo = item.getString("logo");
                String orderId = item.getString("applyNo");
                String companyName = item.getString("companyName");
                String productName = item.getString("productName");

                //  用户协议
                List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
                    //  获取协议
                    JSONArray listProtocolResult = item.getJSONArray("protocolList");
                    IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                        JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                        ApiProtocol protocol = new ApiProtocol();
                        protocol.setProtocolName(protocolObject.getString("protocolName"));
                        protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                        newList.add(protocol);
                    });
                });

                //  获取手机号掩码
                List<String> listPhoneMd5 = CollUtils.newArrayList(newList -> {
                    JSONArray jsonArray = item.getJSONArray("md5List");
                    IteratorUtils.array(jsonArray, (protocolResult, index) -> {
                        String phoneMd5  = jsonArray.getString(index);
                        newList.add(phoneMd5);
                    });
                });
                RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();

                result.setPrice(price);
                result.setLogoPath(logo);
                result.setApplyId(orderId);
                result.setDisplayName(companyName);
                result.setProductName(productName);
                result.setProtocolList(protocolList);
                result.setListPhoneMd5(listPhoneMd5);
                listRespPlatformPhoneMaskDataExchange.add(result);
            }
        }
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        ApiPlatApplyFuManTongMask apiPlatApplyFuManTong = new ApiPlatApplyFuManTongMask();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        apiPlatApplyFuManTong.setPhone(apiApplyParameter.getPhone());
        apiPlatApplyFuManTong.setRealName(apiApplyParameter.getUserName());
        apiPlatApplyFuManTong.setAge(apiFieldConverter.getAgeInt());
        //  性别
        Integer sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        apiPlatApplyFuManTong.setGender(sex);
        apiPlatApplyFuManTong.setCity(apiApplyParameter.getCity());
        apiPlatApplyFuManTong.setCityCode(apiApplyParameter.getAreaCode());
        //  公积金
        apiPlatApplyFuManTong.setAccumulationFund(apiFieldConverter.hasProvidentFundToNumber());
        //  社保
        apiPlatApplyFuManTong.setSocialSecurity(apiFieldConverter.hasSocialSecurityToNumber());
        //  房产
        apiPlatApplyFuManTong.setHouse(apiFieldConverter.hasRealEstateInfoToNumber());
        //  车
        apiPlatApplyFuManTong.setVehicle(apiFieldConverter.hasCarInfoToNumber());
        //  保单
        apiPlatApplyFuManTong.setInsurance(apiFieldConverter.hasInsurancePolicyToNumber());
        //  描述：芝麻分0:无芝麻分1:600分以下2:600-650分3:650-700分4:700分以上默认1
        Integer zhima = ChooseEq.create(apiApplyParameter.getSesameCredit())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .end(1);
        apiPlatApplyFuManTong.setSesameScore(zhima);
        //  职业身份1-上班族2-公务员/事业单位3-私营业主4-个体户5-其他默认1
        Integer professional = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", 1)
                .when("2", 5)
                .when("3", 3)
                .when("4", 2)
                .when("5", 4)
                .end(1);
        apiPlatApplyFuManTong.setProfessional(professional);
        // ip
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            apiPlatApplyFuManTong.setIp(apiApplyParameter.getIp());
        } else {
            apiPlatApplyFuManTong.setIp("127.0.0.1");
        }
        // 用户客户端
        apiPlatApplyFuManTong.setClient(1);
        //  贷款金额
        apiPlatApplyFuManTong.setAmount(apiFieldConverter.getLoanAmountInt());
        //  借款期限
        Integer loanTerm = ChooseEq.create(apiApplyParameter.getLoanTerm())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .when("5", 5)
                .when("6", 5)
                .end(3);
        apiPlatApplyFuManTong.setLoanTerm(loanTerm);
        //  借款用途1-购房 2-购车 3-住房装修4-教育深造5-休闲旅游6-个人消费7-房租缴纳8-其他贷款默认6*/
        Integer loanUse = ChooseEq.create(apiApplyParameter.getLoanPurpose())
                .when("1", 5)
                .when("2", 4)
                .when("3", 8)
                .when("4", 3)
                .when("5", 8)
                .when("6", 6)
                .end(6);
        apiPlatApplyFuManTong.setLoanUse(loanUse);
        //  信用卡
        Integer creditCard = ChooseEq.create(apiApplyParameter.getCreditLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .when("6", 1)
                .end(0);
        apiPlatApplyFuManTong.setCreditCard(creditCard);
        //  白条
        Integer bt = ChooseEq.create(apiApplyParameter.getBtLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .end(0);
        apiPlatApplyFuManTong.setBaitiao(bt);
        // 花呗
        Integer hb = ChooseEq.create(apiApplyParameter.getHbLimit())
                .when("1", 0)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 2)
                .end(0);
        apiPlatApplyFuManTong.setHuabei(hb);
        //  月收入
        Integer salary = ChooseEq.create(apiApplyParameter.getMonthlySalary())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .when("5", 5)
                .end(2);
        apiPlatApplyFuManTong.setMonthIncome(salary);
        //  工资发放
        Integer salaryMethod = ChooseEq.create(apiApplyParameter.getYearsService())
                .when("1", 1)
                .when("2", 3)
                .when("3", 2)
                .end(2);
        apiPlatApplyFuManTong.setSalaryType(salaryMethod);
        //  月收入
        Integer education = ChooseEq.create(apiApplyParameter.getEducationAttainment())
                .when("1", 1)
                .when("2", 1)
                .when("3", 1)
                .when("4", 2)
                .when("5", 3)
                .when("6", 5)
                .end(2);
        apiPlatApplyFuManTong.setEducation(education);
        //  营业执照
        apiPlatApplyFuManTong.setBusinessLicense(apiFieldConverter.hasBizLicenseYearToNumber());
        // 协议列表
        apiPlatApplyFuManTong.setProtocolList(CollUtils.newArrayList(newList -> {
            ApiPlatApplyFuManTongMask.ProtocolList protocolList = new ApiPlatApplyFuManTongMask.ProtocolList();
            protocolList.setProtocolName("个人信息授权协议");
            protocolList.setProtocolUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
            newList.add(protocolList);
        }));

        AES aes = AES.createEcb(KEY.getBytes());
        String json = JsonUtils.toJson(apiPlatApplyFuManTong);
        String encrypt = aes.encryptToBase64Str(json);
        Map<Object, Object> dataMap = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("content", encrypt);
        });
        return JsonUtils.toJson(dataMap);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}

